package com.webdiy.dfss.impl;

import com.sys.plat.bean.PageBean;
import com.sys.plat.service.base.BaseServiceImpl;
import com.sys.system.Constants;
import com.sys.tool.*;
import com.webdiy.dao.model.DfssPlan;
import com.webdiy.dao.model.DfssUserInfo;
import com.webdiy.dfss.iface.PlanService;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: mabo
 * Date: 2009-11-25
 * Time: 16:27:19
 * To change this template use File | Settings | File Templates.
 */
public class PlanServiceImpl extends BaseServiceImpl implements PlanService {

    public void findPlan(PageBean pageBean) {
        pageBean.setHql("FROM DfssPlan");
        pageBean.setProperty("planDate");
        this.page(pageBean);
    }

    public void savePlan(DfssPlan p) {
        if (p.getId() != null && !p.getId().equals("")) {
            this.dao.updateObject(p);
        } else {
            this.dao.saveObject(p);
        }
    }

    public void delPlan(String[] ids) {
        this.delObject(ids, DfssPlan.class);
    }


    public DfssUserInfo start(final DfssUserInfo u) {
        //final DfssUserInfo u = (DfssUserInfo) HttpUtil.sessionGetAttr("dfssUserInfo");
        final List<DfssPlan> planList = this.dao.listByHql("FROM DfssPlan WHERE userId = ?", u.getId());


        Thread th = new Thread(new Runnable() {
            public void run() {


                HttpClientTool hct = new HttpClientTool();
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                list.add(new BasicNameValuePair("edtStudentID", u.getUserCode()));
                list.add(new BasicNameValuePair("edtPassword", u.getUserPassWord()));
                list.add(new BasicNameValuePair("__EVENTTARGET", "btnSearch"));
                list.add(new BasicNameValuePair("__VIEWSTATE", "dDwtMzQ5NDE2NDMwO3Q8O2w8aTwyPjs+O2w8dDw7bDxpPDk+Oz47bDx0PHA8bDx2YWx1ZTs+O2w86KejICDplIE7Pj47Oz47Pj47Pj47PohG/2GfWW4iDo4FkpwpstcnUecB"));
                hct.post("http://yueche.dfss.cn/web/cmp/login.aspx", list);


                String htmlBody = "";
                String grid = "";
                String date = "";

                StringTool st = new StringTool();
                StringTool tdSt = new StringTool();
                StringTool okSt = new StringTool();


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


                while (true) {
                    hct.setUrl("http://yueche.dfss.cn/web/cmp/yc.aspx?StudentID=" + u.getUserCode());

                    htmlBody = hct.getInnerHTML();

                    planBreak:
                    for (DfssPlan plan : planList) {
                        st.setMatcher(htmlBody);


                        Calendar c = Calendar.getInstance();

                        int week = c.get(Calendar.DAY_OF_WEEK);


                        if (plan.getPlanDate().equals(sdf.format(new Date()))) {//如果日期等于当日，则不预约
                            log.warn("日期等于当日，不预约   :" + plan.getPlanDate());
                            break planBreak;
                        }


                        if (plan.getToday() == 1) {
                            if (plan.getPlanDate().equals(sdf.format(c.getTime()))) {//如果日期等日次日，则不预约
                                log.warn("日期等日次日，不预约   :" + plan.getPlanDate());
                                break planBreak;
                            }
                        }

                        if (plan.getPlanDate().equals(String.valueOf(week))) {//如果星期等于次日，则不预约
                            log.warn("星期等于当日，不预约   :" + plan.getPlanDate());
                            break planBreak;
                        }


                        if (plan.getToday() == 1) {
                            if (week == 7) {
                                week = 1;
                            } else {
                                week++;
                            }
                            if (plan.getPlanDate().equals(String.valueOf(week))) {//如果星期等于次日，则不预约
                                log.warn("星期等于次日，不预约   :" + plan.getPlanDate());
                                break planBreak;
                            }
                        }


                        date = plan.getPlanDate();

                        int sw = 0;
                        try {
                            sw = Integer.valueOf(plan.getPlanDate());
                        } catch (NumberFormatException e) {
                            log.debug("具体日期，不是星期");
                        }
                        switch (sw) {
                            case 2:
                                date = "星期一";
                                break;
                            case 3:
                                date = "星期二";
                                break;
                            case 4:
                                date = "星期三";
                                break;
                            case 5:
                                date = "星期四";
                                break;
                            case 6:
                                date = "星期五";
                                break;
                            case 7:
                                date = "星期六";
                                break;
                            case 1:
                                date = "星期天";
                                break;
                        }

                        st.setPattern("<td[^>]*?id='([^']*?)'[^>]*?><nobr>([\\d()\\S]*)" + date + "([\\d()\\S]*)</nobr></td>");
                        if (!st.isFind()) {
                            continue;
                        }
                        grid = st.getValue(1);
                        grid = grid.substring(0, grid.length() - 1);
                        grid = grid + plan.getPlanTime();

                        st.setPattern("<td[^>]*?id='" + grid + "'([^>])*?>(.*?)</td>");
                        if (st.isFind()) {
                            if (!st.getValue(2).equals("")) {
                                String tdValue = st.getValue(2);
                                log.warn("user : " + u.getUserCode() + "日期捕获成功  == " + date);

                                tdSt.setMatcher(tdValue);
                                tdSt.setPattern("<input(.)*id=\"(.*?)\"(.)*02.gif(.)*/>");
                                if (tdSt.isFind()) {
                                    log.warn("user : " + u.getUserCode() + "捕获成功 +" + date + plan.getPlanTime());


                                    List<NameValuePair> listPair = new ArrayList<NameValuePair>();
                                    listPair.add(new BasicNameValuePair(tdSt.getValue(2).replaceAll("grid_", "grid:").replaceAll("_imgButton", ":imgButton") + ".x", "1"));
                                    listPair.add(new BasicNameValuePair(tdSt.getValue(2).replaceAll("grid_", "grid:").replaceAll("_imgButton", ":imgButton") + ".y", "1"));
                                    okSt.setMatcher(htmlBody);
                                    okSt.setPattern("<input(.)*name=\"__VIEWSTATE\"(.)*value=\"(.*?)\"(.)*/>");
                                    listPair.add(new BasicNameValuePair("__VIEWSTATE", okSt.getValue(3).toString()));

                                    listPair.add(new BasicNameValuePair("gridgrid", "%3CDisplayLayout%3E%3CStateChanges%3E%3CStateChange%20Type%3D%22ActiveCell%22%20Level%3D%226_3%22%3E%3C/StateChange%3E%3C/StateChanges%3E%3C/DisplayLayout%3E"));

                                    String postValue = hct.post("http://yueche.dfss.cn/web/cmp/yc.aspx?StudentID=" + u.getUserCode(), listPair);

                                    String postCs = "__VIEWSTATE = " + okSt.getValue(3).toString() + " \n\n\n ";
                                    postCs = postCs + tdSt.getValue(2).replaceAll("grid_", "grid:").replaceAll("_imgButton", ":imgButton") + ".x" + " \n\n\n";
                                    postCs = postCs + tdSt.getValue(2).replaceAll("grid_", "grid:").replaceAll("_imgButton", ":imgButton") + ".y" + " \n\n\n";

                                    long stime = System.currentTimeMillis();
                                    FileTool.setFileBody("D:\\IDEA\\dfss\\" + u.getUserCode() + "_" + stime, postValue, "UTF-8");
                                    FileTool.setFileBody("D:\\IDEA\\dfss\\" + u.getUserCode() + "_Post_" + stime, postCs, "UTF-8");


                                    okSt.setMatcher(postValue);
                                    okSt.setPattern("<TR([^']*?)>([^']*?)已预约训练([^']*?)<span([^']*?)>([^']*?)</span>([^']*?)</TR>");
                                    String value1 = "";
                                    if (okSt.isFind()) {
                                        value1 = okSt.getValue(5);
                                    }

                                    okSt.setMatcher(htmlBody);
                                    okSt.setPattern("<TR([^']*?)>([^']*?)已预约训练([^']*?)<span([^']*?)>([^']*?)</span>([^']*?)</TR>");
                                    String value2 = "";
                                    if (okSt.isFind()) {
                                        value2 = okSt.getValue(5);
                                    }

                                    log.warn(value1 + "===" + value2);

                                    if (!value1.equals(value2)) {


                                        log.warn("预订成功");
                                        MailTool mt = new MailTool("mabo@ec.com.cn", "56789mb", "mail.ec.com.cn");
                                        mt.post(u.getUserMail(), "自动约车系统，预订成功【系统邮件】",
                                                " 自动约车系统，预订成功，\n " +
                                                        "时间为：" + value1 + " \n\n " +
                                                        "具体信息请登录系统查阅 \n " +
                                                        "东方时尚系统：\n " +
                                                        "http://yueche.dfss.cn/web/cmp/login.aspx \n\n " +
                                                        "自动约车系统：\n " +
                                                        "http://211.88.30.145:8080/dfss/");

                                        FetionTool.sendSmsByUri(u.getFetionUir(), "自动约车系统，预订成功！时间为：" + value1);
                                    }
                                }
                            }
                        }
                    }
                    log.warn("user : " + u.getUserCode() + " 一次捕获结束");

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        log.warn("user : " + u.getUserCode() + " Thread.sleep(1000);错误");
                    }
                }
            }
        });
        th.start();

        u.setRun(1);//启动运行
        this.dao.updateObject(u);

        Constants.session.put(u.getId(), th);

        return u;
    }


    public DfssUserInfo stop(DfssUserInfo u) {

        //DfssUserInfo u = (DfssUserInfo) HttpUtil.sessionGetAttr("dfssUserInfo");
        if (Constants.session.get(u.getId()) != null) {
            Thread th = (Thread) Constants.session.get(u.getId());
            th.stop();
        }

        u.setRun(2);//停止运行
        this.dao.updateObject(u);
        return u;
    }


    public void systemInit() {
        /*List<DfssUserInfo> listUser = this.dao.listByHql("FROM DfssUserInfo WHERE run = 1");
        for (DfssUserInfo userInfo : listUser) {
            this.start(userInfo);
        }*/

        Thread th = new Thread(new Runnable() {
            public void run() {
                while (true) {


                    Thread thRun;
                    /*for (Object o : Constants.session.keySet()) {
                        thRun = (Thread) Constants.session.get(o);
                        DfssUserInfo dui = (DfssUserInfo) dao.getObject(DfssUserInfo.class, o.toString());
                        if (dui != null) {
                            if (dui.getRun() == 1) {
                                if (!thRun.isAlive()) {
                                    thRun.start();
                                }
                            } else {
                                thRun.stop();
                                Constants.session.remove(o);
                            }
                        } else {
                            thRun.stop();
                            Constants.session.remove(o);
                        }
                    }*/


                    List<DfssUserInfo> listUser = dao.listByHql("FROM DfssUserInfo");
                    for (DfssUserInfo u : listUser) {
                        if (u.getRun() == 1) {//启动监视状态
                            if (Constants.session.containsKey(u.getId())) {//检查是否在线程集合中
                                thRun = (Thread) Constants.session.get(u.getId());//取得线程
                                if (!thRun.isAlive()) {//判断是否为启动状态
                                    thRun.start();
                                }
                            } else {//未在线程集合中，但数据为启动监视状态，创建线程
                                start(u);
                            }
                        } else {//未启动监视状态
                            if (Constants.session.containsKey(u.getId())) {//检查是否在线程集合中
                                thRun = (Thread) Constants.session.get(u.getId());//取得线程
                                thRun.stop();
                            }
                        }

                    }


                    log.warn("守护线程：清理一次完毕");

                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {

                    }


                }
            }
        });
        th.start();
    }
}
